package com.lugora.bi.manager;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.lugora.bi.common.ErrorCode;
import com.lugora.bi.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class AiManager {

    @Value("${chatgpt.secretKey}")
    private String secretKey;

    @Value("${chatgpt.requestUrl}")
    private String requestUrl;

    @Value("${chatgpt.model}")
    private String model;

    @Value("${chatgpt.timeout}")
    private Integer timeout;

    private final String prefix = "你是一个数据分析师，要生成一个可以使用的 echarts 5.5.1 版本的 javascript 代码，接下来我会给你我要求的输出格式、分析目标和原始数据，请告诉我分析结论\n" +
            "        输出格式(必须严格按照我的输出格式输出):\n" +
            "        【【【【【【\n" +
            "        没有注释和换行符的 echarts 5.5.1 版本的折线图 javascript 代码 举个例子:" +
            "option = {xAxis: {type: 'category',data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']},yAxis: {type: 'value'},series: [{data: [150, 230, 224, 218, 135, 147, 260],type: 'line'}]};" +
            "        【【【【【【\n" +
            "        数据分析结论(纯文本格式即可, 不要换行符, 不用写'数据分析结论'这几个字, 使用中文)\n" +
            "        \n";

    class Msg {
        public Msg(String role, String content) {
            this.role = role;
            this.content = content;
        }

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        private String role;
        private String content;
    }

    public String chatForCode(String goal, String originalData) {
        Map<String, Object> hashMap = new HashMap<>();

        List<Msg> messages = new ArrayList<>();
        Msg msg = new Msg("user", prefix + "分析目标: " + goal + "\n" + "原始数据:\n" + originalData);
        messages.add(msg);

        hashMap.put("messages", messages);
        hashMap.put("model", model);

        String json = JSONUtil.toJsonStr(hashMap);
        log.info("Request JSON: {}", json);

        try {
            String response = HttpRequest.post(requestUrl)
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + secretKey)
                    .body(json)
                    .timeout(timeout)
                    .execute()
                    .body();

            if (response == null) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI 响应错误");
            }

            JsonObject jsonObject = JsonParser.parseString(response).getAsJsonObject();

            String content = jsonObject.getAsJsonArray("choices")
                    .get(0).getAsJsonObject()
                    .getAsJsonObject("message")
                    .get("content").getAsString();

            return content;
        } catch (RuntimeException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请求超时, 请稍后重试");
        }
    }
}
